const util = require('../../../utils/util.js');
var xrRequest = require("../../../vendor/hope-sdk/core/request");
var config = require('../../../config');
const app = getApp();
Page({
  data: {
    logined: false,
    authsetting: 0,
    userinfo: null,
    userDetail: null,
    hostUrl: config.service.host,
    showSexActionSheet: false,
    itemSexList: [{
      text: "女",
      color: "#1a1a1a"
    }, {
      text: "男",
      color: "#1a1a1a"
    }
    ]
  },
  onLoad: function (options) {
    var _this = this;
    app.pageOnLoadInit(this, true).then(function (res) {
      //这里写验证登录成功后且无需验证授权 需要执行的逻辑
      //若还需验证授权成功才执行的逻辑需写在onShow方法里面，
      //并且这里pageOnLoadInit()第二个参数要为 true
      console.log(res);
    }, function (error) {
      // 登录失败
      wx.showModal({
        title: "Error",
        content: error.errMsg ? error.errMsg : 'Fail to login.Please feedback to manager.',
      });
      return false;
    });

  },
  onShow: function () {
    var that = this
    app.pageOnShowInit(that).then(function () {
      //这里写验证授权成功后 需要执行的逻辑
      that.initUserInfo();
    }, function () {
      //用户没有授权
      console.warn('Auth scope.userInfo is unable.');
      return false;
    });
  },
  initUserInfo: function () {
    var that = this;
    xrRequest.request(app,{
      url: config.service.getUserDetail,
      login: true,
      success: function (res) {
        that.setData({
          userDetail: res.data.data,
        });
      },
      authfail: function (e) {
        wx.redirectTo({
          url: "../../auth/auth"
        })
      },
    });
  },
  updateUserInfo: function (data) {
    xrRequest.request(app,{
      url: config.service.modifyInfo,
      login: true,
      data: data,
      success: function (res) {
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          });
          app.globalData.authsetting = 1;
          app.globalData.userinfo = res.data.data;
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2]; //上一个页面
          prevPage.setData({
            'userinfo': res.data.data,
            'authsetting': 1
          });
        }
      },
      authfail: function (e) {
        wx.redirectTo({
          url: "../../auth/auth"
        })
      },
    });
  },
  openSexActionSheet: function (e) {
    this.setData({
      showSexActionSheet: true
    })
  },
  closeSexActionSheet: function () {
    this.setData({
      showSexActionSheet: false
    })
  },
  itemSexClick: function (e) {
    let index = e.detail.index;
    this.closeSexActionSheet();
    //util.toast(`您点击的按钮索引为：${index}`)
    let gender = `userDetail.gender`;
    this.setData({
      [gender]: index
    });
    //this.updateUserInfo("gender", index);
  },
  bindDateChange: function (e) {
    console.log(e);
    var value = e.detail.value;
    if (util.isNullOrEmpty(value)) {
      util.toast("未选择日期~");
      return;
    }
    let birthday = `userDetail.birthday`;
    this.setData({
      [birthday]: value
    });
    //this.updateUserInfo("birthday", value);
  },
  chooseImage: function () {
    let _this = this;
    wx.chooseImage({
      count: 1,
      success: function (e) {
        console.log(e);
        let path = e.tempFilePaths[0];
        _this.uploadImage(path).then((url) => {
          //_this.change()
          console.log('上传成功');
          //util.toast("上传成功" + url);
          let avatar = `userDetail.avatar`;
          _this.setData({
            [avatar]: url
          });
          //_this.updateUserInfo("avatar", url);
        }).catch((e) => {
          //_this.change()
          console.log(e);
          util.toast("上传失败");
        })
      }
    })
  },
  uploadImage: function (url) {
    let _this = this;
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: config.service.upload,
        name: "file",
        header: config.header,
        formData: {},
        filePath: url,
        success: function (res) {
          console.log(res)
          if (res.statusCode == 200) {
            //返回结果 此处需要按接口实际返回进行修改
            let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
            //判断code，以实际接口规范判断
            if (d.code % 100 === 1 && d.data && d.data.url) {
              // 上传成功 d.url 为上传后图片地址，以实际接口返回为准
              var url = d.data.url;
              resolve(url);
              return;
            }
            reject()
          } else {
            reject()
          }
        },
        fail: function (res) {
          reject()
        }
      })
    })
  },
  bioInput: function (e) {
    let bio = `userDetail.bio`;
    this.setData({
      [bio]: e.detail.value
    });
  },
  nicknameInput: function (e) {
    let nickname = `userDetail.nickname`;
    this.setData({
      [nickname]: e.detail.value
    });
  },
  realnameInput:function(e){
    let realname = `userDetail.realname`;
    this.setData({
      [realname]: e.detail.value
    });
  },
  submitHandler: function (e) {
    var detail = this.data.userDetail;
    var data = {};
    if (!util.isNullOrEmpty(detail.avatar)) {
      data.avatar = detail.avatar;
    }
    if (!util.isNullOrEmpty(detail.realname)) {
      data.realname = detail.realname;
    }
    if (!util.isNullOrEmpty(detail.nickname)) {
      data.nickname = detail.nickname;
    }
    if (!util.isNullOrEmpty(detail.gender)) {
      data.gender = detail.gender;
    }
    if (!util.isNullOrEmpty(detail.birthday)) {
      data.birthday = detail.birthday;
    }
    if (!util.isNullOrEmpty(detail.bio)) {
      data.bio = detail.bio;
    }
    this.updateUserInfo(data);
  }
})